package com.kusej.dbdocexport.utils;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class FileUtils {
    public static void saveString(Path savePath, String content){
        try {
            Files.deleteIfExists(savePath);
            Files.createDirectories(savePath.getParent());
            Files.createFile(savePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try (BufferedWriter bufferedWriter = Files.newBufferedWriter(savePath, StandardOpenOption.WRITE)){
            bufferedWriter.write(content);
            bufferedWriter.flush();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static String readStreamFromResource(String resource) {
        try(InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream(resource)){
            if (inputStream == null){
                throw new RuntimeException("读取到的文件流为空 " + resource);
            }
            int length;
            byte[] bytes = new byte[1024];
            try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){
                while ((length = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, length);
                }
                return outputStream.toString();
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
